<template>
	<view>
		<cu-custom bgColor="bg-blue" :isBack="true">
			<block slot="content">发布</block>
		</cu-custom>
		<view class="cu-form-group">
			<view class="title">标题</view>
			<input type="text" v-model="imageInfo.title" placeholder="请输入图片标题" autocomplete="off" />
		</view>
		<view class="cu-form-group">
			<view class="title" style="top: -24px;">描述</view>
			<textarea maxlength="-1" placeholder="请输入图片描述" autocomplete="off"
				v-model="imageInfo.description"></textarea>
			<!-- <input type="text" v-model="imageInfo.description" placeholder="请输入图片描述" autocomplete="off" /> -->
		</view>
		<view class="cu-form-group">
			<view class="title">标签</view>
			<input type="text" v-model="imageInfo.label" placeholder="请输入图片标签" autocomplete="off" />
		</view>
		<view class="cu-bar bg-white margin-top">
			<view class="action">图片上传</view>
		</view>
		<view class="cu-form-group">
			<view class="grid col-4 grid-square flex-sub">
				<view class="bg-img" v-for="(item, index) in imgList" :key="index" @tap="ViewImage"
					:data-url="imgList[index].tempFilePaths[0]">
					<image :src="imgList[index].tempFilePaths[0]" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index"><text
							class="cuIcon-close"></text></view>
				</view>
				<view class="solids" @tap="ChooseImage" v-if="imgList.length < 1"><text class="cuIcon-cameraadd"></text>
				</view>
			</view>
		</view>
		<view class="padding flex flex-direction"><button @click="handleSubmit" class="cu-btn bg-blue lg">提交</button>
		</view>
	</view>
</template>

<script>
	import {
		checkTokenInStore
	} from '../../permission/index';
	import {
		addImageApi,
		fetchOssTokenApi
	} from '../../api/http';
	import {
		mapState
	} from 'vuex';
	import OSS from '@/lib/aliyun-oss-sdk-6.13.2.min.js';
	export default {
		data() {
			return {
				imageInfo: {
					url: '',
					title: '',
					description: '',
					label: '',
					createdBy: null,
					updatedBy: null
				},
				imgList: []
			};
		},
		onLoad: () => {
			checkTokenInStore();
		},
		computed: {
			...mapState({
				userInfo: state => state.userInfo,
				token: state => state.token
			})
		},
		methods: {
			resetData() {
				this.imageInfo = {
					url: '',
					title: '',
					description: '',
					label: '',
					createdBy: null,
					updatedBy: null
				};
				this.imgList = [];
			},
			ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: res => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res);
						} else {
							this.imgList = [res];
						}
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList.map((item) => item.tempFilePaths),
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1);
						}
					}
				});
			},
			showToastWithMsg(msg) {
				uni.showToast({
					title: msg,
					duration: 1000,
					icon: 'none'
				});
			},
			handleSubmit() {
				if (this.imageInfo.title === '') {
					this.showToastWithMsg('请输入图片标题');
					return;
				}
				if (this.imageInfo.description === '') {
					this.showToastWithMsg('请输入图片描述');
					return;
				}
				if (this.imageInfo.label === '') {
					this.showToastWithMsg('请添加图片标签');
					return;
				}
				if (this.imgList.length <= 0) {
					this.showToastWithMsg('请选择要上传的图片');
					return;
				}
				fetchOssTokenApi().then(res => {
					const tokenInfo = res.data;
					let client = new OSS({
						region: tokenInfo.region,
						accessKeyId: tokenInfo.accessKeyId,
						accessKeySecret: tokenInfo.accessKeySecret,
						stsToken: tokenInfo.securityToken,
						bucket: tokenInfo.bucket
					});
					//上传文件
					const name = this.imgList[0].tempFiles[0].name
					let strs = name.split(".")
					const filename = tokenInfo.uuid + "." + strs[strs.length - 1]
					let curTime = new Date();
					let year = curTime.getFullYear(),
						month = curTime.getMonth() + 1,
						day = curTime.getDate()
					let dir = year + '/' + (month < 10 ? '0' + month : month) + '/' + (day < 10 ? '0' + day :
						day) + '/'
					this.h5UrlToBlob(this.imgList[0].tempFilePaths[0])
						.then(b => {
							uni.showLoading({
								title: '加载中...',
								mask: true
							})
							client.put(dir + filename, b)
								.then(res => {
									// console.log(res)
									uni.hideToast();
									this.imageInfo.createdBy = this.userInfo.id;
									this.imageInfo.updatedBy = this.userInfo.id;
									this.imageInfo.url = res.url;
									addImageApi(this.imageInfo).then(res => {
										this.resetData();
										uni.redirectTo({
											url: '../image_details/image_details?id=' + res
												.data,
											success: () => {
												uni.showToast({
													title: '上传成功',
													duration: 1000
												});
											}
										});
									});
								}).catch(err => {
									console.log(err)
									uni.hideToast();
									uni.showToast({
										title: "网络忙，上传失败",
										icon: "none"
									})
								})
						})
				});
			},
			h5UrlToBlob(url) {
				return new Promise((resolve, reject) => {
					var xhr = new XMLHttpRequest();
					xhr.open('GET', url, true);
					xhr.responseType = 'blob';
					xhr.onload = function(e) {
						if (this.status == 200) {
							var blob = this.response;
							// console.log(myBlob)
							resolve(blob)
							// myBlob现在是对象URL指向的blob。 
						}
					};
					xhr.send();
				})
			}
		}
	};
</script>

<style></style>
